package com.anjoyo.xgh.musicshare.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.anjoyo.xgh.musicshare.R;
import com.anjoyo.xgh.musicshare.api.ShareApi;
import com.anjoyo.xgh.musicshare.entry.Song;
import com.anjoyo.xgh.musicshare.entry.User;
import com.anjoyo.xgh.musicshare.util.BitmapUtil;
import com.anjoyo.xgh.musicshare.util.Constant;
import com.anjoyo.xgh.musicshare.util.MusicSpf;
import com.anjoyo.xgh.musicshare.util.StringUtil;

public class ShareAct extends Activity {
	private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
	private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中
	private static final int PHOTO_REQUEST_CUT = 3;// 结果

	File tempFile = new File(Environment.getExternalStorageDirectory(),
			StringUtil.getPhotoFileName());
	String UPLOADPATH = Constant.CACHE + "share.png";
	ImageView shareimg, send, ivback,ivrecord,recordview;
	EditText sharetxt;
	TextView textView,tvplay;
	Button button;
	Context con;
	int whichimg = -1;
	File imgFile;
	String filepath;
	String imgurl;
	int musicid;

	double lat = 103.990;
	double lon = 30.587;
	LocationManager manager;
	Location location;
	String address = "中国";

	PopupWindow popupWindow;
	private static final File Record_DIR = new File(Constant.RECORD_PATH);
	private MediaRecorder mediaRecorder;
	private File audioFile = new File(Record_DIR + "/" + "RECORD" + ".amr");
	private MediaPlayer player;
	private Timer timer;
	private MyTimerTask myTimerTask;
	private boolean isPlay = false;
	private static final int VOICE_AMPLITUDE_01 = 1000;
	private static final int VOICE_AMPLITUDE_02 = 4000;
	private static final int VOICE_AMPLITUDE_03 = 10000;
	private static final int VOICE_AMPLITUDE_04 = 18000;
	private static final int VOICE_AMPLITUDE_05 = 25000;
	public long starttime,endtime;
	public int time=-1;
	
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == Constant.MSG_SHARE_OK) {
				JSONObject object = (JSONObject) msg.obj;
				if (msg.arg1 == 200) {
					Toast("分享成功");
					if (audioFile.exists()) {
						audioFile.delete();
					}
					finish();
				} else {
					try {
						Toast("分享失败|" + object.getString("msg"));
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
//				System.out.println(msg.obj.toString());
			}
			if (msg.what == Constant.DOWLOAD_OK) {
				Toast("图片下载成功");
				whichimg = 1;
				shareimg.setImageURI(Uri.parse(filepath));
			}
			if (msg.what == 110) {
				changeImage();
			}
			super.handleMessage(msg);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.share_layout);
		send = (ImageView) findViewById(R.id.iv_send);
		ivback = (ImageView) findViewById(R.id.iv_back);
		sharetxt = (EditText) findViewById(R.id.et_share);
		textView = (TextView) findViewById(R.id.tv_zs);
		shareimg = (ImageView) findViewById(R.id.iv_shareimg);
		button = (Button) findViewById(R.id.btn_local);
		ivrecord = (ImageView) findViewById(R.id.iv_record);
		tvplay =(TextView) findViewById(R.id.tv_play);
		con = this;
//		load();
		Intent intent = getIntent();
		Song song = (Song) intent.getSerializableExtra("song");
		if (song !=null) {
			sharetxt.setText("分享-" + song.getName() + "-" + song.getArtist());
			musicid = song.getMusicid();
			//imgurl转码后的歌手图片url
			String img = StringUtil.zhuanma(song.getImage_url());
			imgurl = Constant.SINGER_URL + img + ".jpg";
			
			filepath = Constant.SINGER_IMG + song.getImage_url() + ".jpg";
			if (img != "") {
				File imFile = new File(filepath);
				if (imFile.exists() && imFile.length() > 10) {
					whichimg = 1;
					shareimg.setImageURI(Uri.parse(filepath));
				} else {
					new BitmapUtil().saveNetImg(imgurl, filepath, handler);
				}
			}
		}
		

		send.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				User user = MusicSpf.getloginUser(con);
				if (whichimg == 2) {
					imgFile = new File(UPLOADPATH);
					new ShareApi(handler).share(user.getId(), sharetxt
							.getText().toString(), imgFile, address, musicid,
							lat, lon,audioFile,time);
					System.out.println("自选图片");
				} else if (whichimg == -1) {
					new ShareApi(handler).sharetxtonly(user.getId(), sharetxt
							.getText().toString(),address,lat,lon);
					System.out.println("无图片id:" + user.getId());
				} else if (whichimg == 1) {
					imgFile = new File(filepath);
					new ShareApi(handler).share(user.getId(), sharetxt
							.getText().toString(), imgFile, address, musicid,
							lat, lon,audioFile,time);
					System.out.println("歌手图片");
				}
			}
		});
		shareimg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ChosePhotosDialog();
			}
		});
		InitLocation();
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				System.out.println("获取位置");
				address = loadaddress();
				button.setText("位置：" + address);
			}
		});
		sharetxt.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				textView.setText(sharetxt.getText().length() + "/140");
				return false;
			}
		});
		init();
		initpop();
		ivrecord.setOnLongClickListener(new OnLongClickListener() {
			
			@Override
			public boolean onLongClick(View v) {
				System.out.println("长按");
				popupWindow.showAtLocation(findViewById(R.id.main_layout), Gravity.CENTER, 0, 0);
				startrecord();
				return false;
			}
		});
		ivrecord.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction()==MotionEvent.ACTION_UP) {
					stoprecord();
					tvplay.setVisibility(View.VISIBLE);
			}
				return false;
			}
		});
		tvplay.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (audioFile != null) {
					if (!isPlay) {
						playRecord(audioFile);
					} else {
						player.stop();
						isPlay = false;
					}
				}
				
			}
		});
		tvplay.setOnLongClickListener(new OnLongClickListener() {
			
			@Override
			public boolean onLongClick(View v) {
				if (audioFile.exists()) {
					audioFile.delete();
					tvplay.setVisibility(View.GONE);
				}
				return false;
			}
		});
	}
	
	//第三方调用
	public void Toast(String msg) {
		Toast.makeText(con, msg, Toast.LENGTH_SHORT).show();
	}
	
	public void load() {
		String text=getIntent().getStringExtra(Intent.EXTRA_TEXT);
		System.out.println(text);
		Uri uri=getIntent().getParcelableExtra(Intent.EXTRA_STREAM);
		if (uri!=null) {
			System.out.println(uri.getPath());
		}else {
			System.out.println("kong");
		}
		if (text!=null) {
			sharetxt.setText(text);
			if (uri!=null) {
				filepath=uri.getPath();
				shareimg.setImageBitmap(BitmapFactory.decodeFile(uri.getPath()));
				return ;
			}
		}
	}
	
	/***********************************************************************/
	private void init() {
		timer = new Timer();
		player = new MediaPlayer();
	}
	public void initpop() {
		View view = getLayoutInflater().inflate(R.layout.pop_layout, null);
		recordview = (ImageView) view.findViewById(R.id.iv_recordview);
		popupWindow = new PopupWindow(view, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
	}
	public void startrecord() {
		if (!Record_DIR.exists()) {
			Record_DIR.mkdirs();// 创建储存目录
		}
		mediaRecorder = new MediaRecorder();
		// 麦克风
		mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
		// 输出格式
		mediaRecorder
				.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
		// 编码格式
		mediaRecorder
				.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
		// 输出文件
		mediaRecorder.setOutputFile(audioFile.getAbsolutePath());
		try {
			// 创建文件
			audioFile.createNewFile();
			mediaRecorder.prepare();
		} catch (Exception e) {
			e.printStackTrace();
		}
		starttime = System.currentTimeMillis();
		mediaRecorder.start();
		myTimerTask = new MyTimerTask();
		timer.schedule(myTimerTask, 0, 200);
	}
	private void stoprecord() {
		if (mediaRecorder != null) {
			mediaRecorder.stop();
			endtime = System.currentTimeMillis();
			mediaRecorder.release();
			mediaRecorder = null;
			Toast.makeText(getApplicationContext(), "录音完毕", Toast.LENGTH_LONG)
					.show();
			if (myTimerTask != null) {
				myTimerTask.cancel();
			}
			time = (int) (endtime-starttime)/1000;
			tvplay.setText("录音"+time);
			tvplay.setVisibility(View.VISIBLE);
		}
		popupWindow.dismiss();
	}
	class MyTimerTask extends TimerTask {

		@Override
		public void run() {
			Message message = new Message();
			message.what = 110;
			handler.sendMessage(message);
		}
	}
	/**
	 * 获取音量振幅
	 * 
	 * @return
	 */
	public int getAmplitude() {
		if (mediaRecorder != null) {
			return (mediaRecorder.getMaxAmplitude());
		} else
			return 0;
	}
	/**
	 * 播放录音
	 * 
	 * @param myPlayFile
	 */
	private void playRecord(File myPlayFile) {
		File file = new File(myPlayFile.toString());
		try {
			FileInputStream fis = new FileInputStream(file);
			player.reset();
			player.setDataSource(fis.getFD());
			player.prepare();
		} catch (Exception e) {
			e.printStackTrace();
		}
		player.start();
		isPlay = true;
	}
	/**
	 * 根据声音动态更改图片
	 */
	private void changeImage() {
		int sound = getAmplitude();
		System.out.println("sound::"+sound);
//		recordview.setVisibility(View.VISIBLE);
		
		if (sound > VOICE_AMPLITUDE_01 && sound < VOICE_AMPLITUDE_02) {
			recordview.setImageResource(R.drawable.record_animate_01);
		} else if (sound >= VOICE_AMPLITUDE_02 && sound < VOICE_AMPLITUDE_03) {
			recordview.setImageResource(R.drawable.record_animate_04);
		} else if (sound >= VOICE_AMPLITUDE_03 && sound < VOICE_AMPLITUDE_04) {
			recordview.setImageResource(R.drawable.record_animate_09);
		} else if (sound >= VOICE_AMPLITUDE_04 && sound < VOICE_AMPLITUDE_05) {
			recordview.setImageResource(R.drawable.record_animate_12);
		} else if (sound >= VOICE_AMPLITUDE_05) {
			recordview.setImageResource(R.drawable.record_animate_14);
		} else {
//			recordview.setVisibility(View.INVISIBLE);
			recordview.setImageResource(R.drawable.record_animate_00);
		}
	}

	/***********************************************************************/
	private void ChosePhotosDialog() {
		new AlertDialog.Builder(con)
				.setTitle("选择头像")
				.setPositiveButton("拍照", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						Intent intent = new Intent(
								MediaStore.ACTION_IMAGE_CAPTURE);
						// 指定调用相机拍照后照片的储存路径
						intent.putExtra(MediaStore.EXTRA_OUTPUT,
								Uri.fromFile(tempFile));
						startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO);
					}
				})
				.setNegativeButton("相册", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						Intent intent = new Intent(Intent.ACTION_PICK, null);
						intent.setDataAndType(
								MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
								"image/*");
						startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
					}
				}).create().show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case PHOTO_REQUEST_TAKEPHOTO:
			startPhotoZoom(Uri.fromFile(tempFile), 320);
			break;
		case PHOTO_REQUEST_GALLERY:
			if (data != null)
				startPhotoZoom(data.getData(), 320);
			break;
		case PHOTO_REQUEST_CUT:
			if (data != null)
				setPicToView(data);
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	// 将进行剪裁后的图片显示到UI界面上
	private void setPicToView(Intent picdata) {
		Bundle bundle = picdata.getExtras();
		if (bundle != null) {
			Bitmap photo = bundle.getParcelable("data");
			BitmapUtil.saveImg(UPLOADPATH, photo);
			shareimg.setImageBitmap(photo);
			imgFile = new File(UPLOADPATH);
			whichimg = 2;
		}
	}

	private void startPhotoZoom(Uri uri, int size) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// crop为true是设置在开启的intent中设置显示的view可以剪裁
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX,outputY 是剪裁图片的宽高
		intent.putExtra("outputX", size);
		intent.putExtra("outputY", size);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, PHOTO_REQUEST_CUT);
	}

	public void InitLocation() {
		manager = (LocationManager) getSystemService(LOCATION_SERVICE);
		// Criteria是“精确度”的意思，Criteria类提供若干个查询条件
		Criteria criteria = new Criteria();
		// 位置解析的精度，高或低
		// 参数： Criteria. ACCURACY_FINE，精确模式；
		// Criteria. ACCURACY_COARSE，模糊模式；
		criteria.setAccuracy(Criteria.ACCURACY_MEDIUM);
		// //是否提供海拔高度信息，是或否
		criteria.setAltitudeRequired(false);
		// 是否提供方向信息，是或否
		criteria.setBearingRequired(false);
		// 是否允许运营商计费，是或否
		criteria.setCostAllowed(false);
		// 电池消耗，无、低、中、高，参数
		// Criteria. NO_REQUIREMENT,Criteria. POWER_LOW,Criteria. POWER_MEDIUM,
		// orCriteria. POWER_HIGH,
		criteria.setPowerRequirement(Criteria.POWER_LOW);
		String provder = manager.getBestProvider(criteria, true);
		location = manager.getLastKnownLocation(provder);
		if (location == null) {
			location = manager
					.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		}
		if (location == null) {
			location = manager
					.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		}
	}

	public String loadaddress() {
		if (location == null)
			return null;
		lat = location.getLatitude();
		lon = location.getLongitude();
		System.out.println(lat + ":" + lon);
		Geocoder geocoder = new Geocoder(con, Locale.getDefault());
		try {
			List<Address> addresses = geocoder.getFromLocation(lat, lon, 5);
			StringBuilder stringBuilder = new StringBuilder();
			if (addresses.size() > 0) {
				Address address = addresses.get(0);
				System.out.println("index:" + address.getMaxAddressLineIndex());
				for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
					stringBuilder.append(address.getAddressLine(i) + ":")
							.append("\n");
				}
				stringBuilder.append(address.getAddressLine(0));
				// stringBuilder.append(address.getPostalCode()).append("_");
				// stringBuilder.append(address.getCountryCode()).append("_");
				// stringBuilder.append(address.getCountryName()).append("_");
				System.out.println(stringBuilder.toString());
			}
			return stringBuilder.toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}
